import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
import Welcome from '../components/Welcome'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: '登录',
    meta: {
      title: '登录'
    },
    component: Login
  },
  {
    path: '/',
    name: '主页',
    redirect: '/welcome',
    meta: {
      title: '主页'
    },
    component: () => import('../components/Home'),
    children: [
      {
        path: 'welcome',
        name: 'welcome',
        meta: {
          title: '主页'
        },
        component: Welcome
      },
      {
        path: 'users',
        name: 'users',
        meta: {
          title: '用户列表'
        },
        component: () => import('../components/user/Users.vue')
      },
      {
        path: 'roles',
        name: 'roles',
        meta: {
          title: '角色列表'
        },
        component: () => import('../components/rights/Roles.vue')
      },
      {
        path: 'rights',
        name: 'rights',
        meta: {
          title: '权限列表'
        },
        component: () => import('../components/rights/Rights.vue')
      },
      {
        path: 'categories',
        name: 'categories',
        meta: {
          title: '商品分类'
        },
        component: () => import('../components/goods/Cate.vue')
      },
      {
        path: 'params',
        name: 'params',
        meta: {
          title: '分类参数'
        },
        component: () => import('../components/goods/Params.vue')
      },
      {
        path: 'goods',
        name: 'goods',
        meta: {
          title: '商品列表'
        },
        component: () => import('../components/goods/Goods.vue')
      },
      {
        path: 'goods/add',
        name: 'add',
        meta: {
          title: '添加商品'
        },
        component: () => import('../components/goods/Add.vue')
      },
      {
        path: 'orders',
        name: 'orders',
        meta: {
          title: '订单列表'
        },
        component: () => import('../components/orders/Orders.vue')
      },
      {
        path: 'reports',
        name: 'reports',
        meta: {
          title: '数据报表'
        },
        component: () => import('../components/reports/Reports.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
  // 登录页面直接放行
  if (to.path === '/login') {
    return next()
  }
  // 获取token
  const token = sessionStorage.getItem('token')
  if (!token) {
    // 无token,强制登录
    Message.warning('请您先登录!')
    return next('/login')
  }
  next()
})

// 后置路由守卫
router.afterEach((to, from) => {
  document.title = to.meta.title
})

export default router
